<template>
  <div class="wrap-container">
    <el-row>
      <el-col :span="19">
        <div class="card_left">
          <el-card>
            <el-form ref="formRef" :rules="rules" :model="form" label-width="100px">
              <div class="manage_tit manage_tit_flex">
                <div class="line_box">
                  <div class="line"></div>
                  <p>{{ activeName == '0' ? '编辑优惠券' : '编辑卡券' }}</p>
                </div>
                <div class="approval_btn">
                  <el-button @click="goBack" size="small">返回</el-button>
                </div>
              </div>
              <div class="card_coupon" v-if="activeName == '0'">
                <div
                  v-for="(dict, index) in dict?.type?.coupon_type"
                  :key="index"
                  @click="handleTypeClick(dict)"
                >
                  <div :class="['type_coupon', { active: form.type == dict.value }]">
                    <div class="type_title">{{ dict.label }}</div>
                    <div class="type_content">{{ dict.raw.remark }}</div>
                  </div>
                </div>
                <div>
                  <div class="type_coupon">
                    <div class="type_title">更多优惠券</div>
                    <div class="type_content">敬请期待</div>
                  </div>
                </div>
              </div>
              <div class="card_coupon" v-else-if="activeName == '1'">
                <div
                  v-for="(dict, index) in dict?.type?.pass_type"
                  :key="index"
                  @click="handleTypeClick(dict)"
                >
                  <div :class="['type_coupon', { active: form.type == dict.value }]">
                    <div class="type_title">{{ dict.label }}</div>
                    <div class="type_content">{{ dict.raw.remark }}</div>
                  </div>
                </div>
                <div>
                  <div class="type_coupon">
                    <div class="type_title">更多卡券</div>
                    <div class="type_content">敬请期待</div>
                  </div>
                </div>
              </div>
              <div class="divider"></div>

              <span class="form-title">*基本信息</span>
              <el-form-item label="优惠券名称" prop="name">
                <el-input
                  v-model="form.name"
                  placeholder="请填写优惠券名称"
                  maxlength="20"
                  show-word-limit
                  clearable
                />
              </el-form-item>
              <el-form-item label="渠道备注">
                <el-input
                  v-model="form.mname"
                  placeholder="请填写渠道备注"
                  maxlength="20"
                  show-word-limit
                  clearable
                />
              </el-form-item>
              <el-form-item label="场馆备注">
                <el-input
                  v-model="form.bname"
                  placeholder="请填写场馆备注"
                  maxlength="20"
                  show-word-limit
                  clearable
                />
              </el-form-item>
              <el-form-item label="发布渠道" prop="sourceType">
                <el-select
                  style="width: 100%"
                  filterable
                  clearable
                  v-model="form.sourceType"
                  placeholder="请选择发布渠道"
                >
                  <el-option
                    v-for="dict in dict?.type?.platform_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="Number(dict.value)"
                  />
                </el-select>
              </el-form-item>
              <el-form-item
                label="优惠券面值"
                prop="faceValue"
                v-if="activeName == '0' && form.type != '2'"
              >
                <div class="div_group">
                  <!-- <el-radio v-model="form.money.moneyType" label="1"> -->
                  <el-input
                    style="width: 125px"
                    v-model="form.faceValue"
                    type="number"
                    placeholder="¥ 0.00"
                    clearable
                  />
                  <span class="ml-15px">元</span>
                  <!-- </el-radio> -->
                </div>
              </el-form-item>

              <el-form-item
                label="使用条件"
                prop="thresholdAmount"
                v-if="activeName == '0' && form.type == '3'"
              >
                <!-- <el-radio-group v-model="form.use.useType"> -->
                <!--                  <el-radio label="1">无门槛</el-radio>-->
                <!-- <el-radio label="2"> -->
                <span class="mr-15px">订单满</span>
                <el-input
                  style="width: 70%"
                  v-model="form.thresholdAmount"
                  type="number"
                  placeholder="最低金额"
                  clearable
                />
                <span class="ml-15px">元</span>
                <!-- </el-radio>
                </el-radio-group> -->
              </el-form-item>
              <span class="form-title" v-if="activeName == '1'">*卡券设置</span>

              <el-form-item
                label="卡券类型"
                prop="card.cardType"
                class="limit_item"
                v-if="activeName == '1' && false"
              >
                <el-radio-group v-model="form.card.cardType" disabled>
                  <el-radio label="1">次卡</el-radio>
                  <el-radio label="2">周卡</el-radio>
                  <el-radio label="3">月卡</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="使用次数" prop="totalCount" v-if="activeName == '1'">
                <el-input
                  v-model="form.totalCount"
                  type="number"
                  placeholder="请填写使用次数"
                  clearable
                />
              </el-form-item>
              <el-form-item label="每天限次" prop="dailyLimit" v-if="activeName == '1'">
                <el-input
                  v-model="form.dailyLimit"
                  type="number"
                  placeholder="请填写每天限次"
                  clearable
                />
              </el-form-item>
              <el-form-item
                label="抵扣时长"
                prop="freeHours"
                v-if="activeName == '1' || (activeName == '0' && form.type == '2')"
              >
                <el-input
                  v-model="form.freeHours"
                  type="number"
                  placeholder="请填写抵扣时长"
                  clearable
                >
                  <template #append>小时</template>
                </el-input>
              </el-form-item>
              <el-form-item label="其他说明">
                <el-input
                  type="textarea"
                  :autosize="{ minRows: 4, maxRows: 10 }"
                  placeholder="请输入优惠券相关说明（非必填项）"
                  v-model="form.remark"
                  clearable
                >
                </el-input>
              </el-form-item>
              <div class="footer">
                <el-button type="primary" class="approval_btn" @click="handleSubmit"
                  >提交审核</el-button
                >
                <el-button @click="handleClose">取消</el-button>
              </div>
            </el-form>
          </el-card>
        </div>
      </el-col>
      <el-col :span="5">
        <div class="card_right">
          <el-card v-loading="historyLoading">
            <div class="order_top">
              <div class="manage_tit">
                <div class="line"></div>
                <p>优惠券追踪</p>
              </div>
            </div>
            <div class="track_list">
              <div class="track_item" v-for="item in recordList" :key="item.id">
                <p class="create_time">{{ item.createTime }}</p>
                <div class="track_cont">
                  <p v-if="item.type == null">{{ item.userName }} {{ item.stepName }}</p>
                  <template v-else>
                    <p>
                      {{ item.userName }}
                      <span class="text-color-808080">审核</span>
                      <span :style="{ color: item.stepColor }">{{
                        item.type == 1 ? '通过' : '驳回'
                      }}</span>
                    </p>
                    <p class="text-color-808080 text-xs mt-2px" v-if="item.type == 2">
                      说明：{{ item.stepName }}
                    </p>
                  </template>
                </div>
              </div>
            </div>
          </el-card>
        </div>
      </el-col>
    </el-row>
    <approval-dialog ref="approvalDialogRef" @sure="goJumpPage"></approval-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useDict } from '@/utils/dict'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import {
  getCoupon,
  getApprovalCoupon,
  getPass,
  getApprovalPass,
  updateCoupon,
  updatePass,
} from '@/api/coupon/coupon'
import { addRedis, getHistoryLog } from '@/api/common/sysCommon'
import { getOperationList } from '@/api/coupon/approval'
import { debounce } from '@/utils'
import approvalDialog from '@/components/Approval/approvalDialog.vue'

// 字典数据
const { dict } = useDict({
  dicts: [
    'site_type',
    'coupon_type',
    'platform_type',
    'sys_normal_disable',
    'history_type',
    'pass_type',
  ],
})

// 定义响应式数据
const route = useRoute()
const router = useRouter()
const formRef = ref<FormInstance | null>(null)
const approvalDialogRef = ref<InstanceType<typeof approvalDialog> | null>(null)

const loading = ref(false)
const activeName = ref('') //0表示优惠券，1表示卡券
const historyLoading = ref(false)
const recordList = ref<any[]>([])

const form = reactive({
  type: '3', //券类型
  name: null as string | null, //优惠券名称
  mname: null as string | null, //m端名
  bname: null as string | null, //b端名
  sourceType: null as number | null, //发布渠道
  faceValue: null as number | null, //优惠券面额
  thresholdAmount: null as number | null, //满减总额度
  freeHours: 1, //抵扣时长
  dailyLimit: 1, //每日限用次数
  totalCount: 1, //卡券总可用次数
  remark: null as string | null, //其他说明
  card: {
    cardType: '1', //卡券类型
    cardUseNum: 1, //卡券使用次数
    cardUseNumDay: 1, // 卡券每天使用次数
    offsetHours: 1, // 抵扣时长
  },
})

const rules = reactive<FormRules>({
  name: [{ required: true, message: '请填写优惠券名称', trigger: 'change' }],
  sourceType: [{ required: true, message: '请选择发布渠道', trigger: 'change' }],
  thresholdAmount: [{ required: true, message: '请选择使用条件', trigger: 'change' }],
  faceValue: [{ required: true, message: '请填写优惠券面值', trigger: 'change' }],
  freeHours: [{ required: true, message: '请填写抵扣时长', trigger: 'change' }],
  dailyLimit: [{ required: true, message: '请填写每日限次', trigger: 'change' }],
  totalCount: [{ required: true, message: '请填写卡券总可用次数', trigger: 'change' }],
})

const processedInput = computed({
  get() {
    return form.name // 返回原始输入值显示在 input 中
  },
  set(value: any) {
    const valid = /^[1-9]\d*$/.test(value) // 验证是否为正整数
    if (valid) {
      form.name = value // 如果是正整数，更新原始输入值
    } else {
      form.name = form.name?.replace(/\D/g, '') || '' // 否则移除非数字字符
    }
  },
})

onMounted(() => {
  if (route.query.type) {
    activeName.value = route.query.type as string
  }
  if (route.query.data) {
    getDetail(route.query.data)
    getRecord()
  } else {
    ElMessage.error('请刷新后重试!')
  }
})

// 获取优惠券操作记录
const getRecord = async () => {
  historyLoading.value = true
  const { data } = await getOperationList({
    couponId: route.query.data,
  })
  recordList.value = data
  historyLoading.value = false
}

// 获取优惠券详情
const getDetail = (val: any) => {
  loading.value = true
  const func =
    activeName.value == '0'
      ? route.query.from == 'approval'
        ? getApprovalCoupon
        : getCoupon
      : route.query.from == 'approval'
        ? getApprovalPass
        : getPass
  func(val)
    .then((res: any) => {
      loading.value = false
      Object.assign(form, res.data)
    })
    .catch((e: any) => {
      loading.value = false
    })
}

// 类型选中变色
const handleTypeClick = (dict: any) => {
  // this.form.discountType = dict.value;
}

// 提交
const handleSubmit = debounce(() => {
  try {
    if (!formRef.value) return
    formRef.value.validate(async (valid) => {
      if (valid) {
        const func = activeName.value == '0' ? updateCoupon : updatePass
        await func(form).then((res: any) => {
          if (approvalDialogRef.value) {
            approvalDialogRef.value.approvalVisible = true
          }
        })
      }
    })
  } catch (e) {
    ElMessage.error((e as Error) || '请求失败，请稍后再试')
  }
}, 1000)

// 保存
const saveForm = () => {
  ElMessageBox.confirm(`是否保存为草稿？`)
    .then(() => {
      const params = {
        value: form,
        // expire: 1140
      }
      return addRedis(params).then((res: any) => {
        localStorage.setItem('couponsDraft', res.msg)
      })
    })
    .then(() => {
      ElMessage.success('操作成功')
    })
    .catch(() => {})
}

// 取消
const handleClose = () => {
  router.go(-1)
}

// 操作历史
const handleHistoryTypeName = (val: any) => {
  let str = '未知'
  dict.type?.history_type?.forEach((item: any) => {
    if (item.value == String(val)) {
      str = item.label
    }
  })
  return str
}

const goJumpPage = () => {
  router.push({ path: '/coupon/approval/couApprovalList' })
}

const goBack = () => {
  router.go(-1)
}
</script>

<style lang="scss" scoped>
:deep(.el-card) {
  height: calc(100vh - 80px);
  overflow-y: auto;
}
:deep(.el-card__body) {
  padding-right: 60px;
}
.el-col:nth-child(2) {
  :deep(.el-card__body) {
    padding-right: 15px;
  }
}
.card_left {
  .card_coupon {
    display: flex;
    margin-top: 15px;
  }

  .type_coupon {
    cursor: pointer;
    width: 206px;
    height: 118px;
    padding: 20px;
    border-radius: 9px;
    background-color: rgba(241, 247, 255, 1);
    text-align: center;
    margin: 0 15px 0 0;

    .type_title {
      font-size: 16px;
      font-weight: 500;
      color: rgba(56, 56, 56, 1);
      margin: 0 0 20px 0;
    }

    .type_content {
      font-size: 14px;
      font-weight: 400;
      color: rgba(128, 128, 128, 1);
    }

    &.active {
      background-color: rgba(9, 136, 251, 1);

      .type_title {
        color: rgba(255, 255, 255, 1);
      }

      .type_content {
        color: rgba(255, 255, 255, 1);
      }
    }
  }

  .divider {
    margin: 15px 0;
    opacity: 1;
    height: 1px;
    background: #e5e5e5;
  }

  .form-title {
    display: block;
    font-size: 14px;
    font-weight: 500;
    color: rgba(42, 130, 228, 1);
    margin-bottom: 15px;
  }

  .div_group {
    margin: 0 0 15px 0;
  }

  .divider_text {
    font-size: 14px;
    font-weight: 400;
    color: rgba(42, 130, 228, 1);
  }

  .button_group {
    font-size: 14px;
    font-weight: 400;
  }
}

.card_right {
  margin: 0 0 0 20px;
  .order_top {
    margin-bottom: 0;
    padding-bottom: 8px;
    border-bottom: 1px solid #e5e5e5;
  }
  .track_list {
    padding: 11px 12px 0;
    .track_item {
      margin-bottom: 11px;
      .create_time {
        color: #808080;
        line-height: 18px;
        font-size: 12px;
        margin-bottom: 2px;
      }
      .track_cont {
        font-size: 14px;
        line-height: 21px;
        margin: 2px 0;
        span {
          margin: 0 8px;
        }
      }
    }
  }
}

.footer {
  text-align: center;
  margin-top: 22px;
  .el-button {
    width: 70px;
    height: 35px;
    border-radius: 8px;
    & + .el-button {
      margin-left: 14px;
    }
  }
  .approval_btn {
    width: 95px;
  }
  .save_btn {
    background: rgba(255, 141, 26, 1);
    border-color: rgba(255, 141, 26, 1);
  }
}

.log_list {
  margin: 10px 0 0 0;

  .log_time {
    font-size: 12px;
    font-weight: 400;
    color: rgba(128, 128, 128, 1);
  }

  .log_text {
    font-size: 14px;
    font-weight: 400;
    color: rgba(56, 56, 56, 1);
    margin-right: 10px;
  }
}
:deep(.el-form) {
  .el-form-item {
    margin-bottom: 15px;
    &.limit_item {
      margin-bottom: 0;
      .div_group {
        margin-bottom: 8px;
      }
    }
    .radio_item {
      margin-bottom: 0;
    }
  }
  .el-form-item__label {
    padding-right: 19px;
  }
  .el-icon--right {
    margin-left: 0;
  }
}
:deep(.el-radio:focus:not(.is-focus):not(:active):not(.is-disabled) .el-radio__inner {
  outline: none;
  box-shadow: none;
}
.manage_tit_flex {
  display: flex;
  justify-content: space-between;
}
.line_box {
  display: flex;
  align-items: center;
}
</style>
